package com.quanshu.exchange.ui.gui.message.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMMessage;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.db.GroupDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.GroupLabelEntity;
import com.quanshu.exchange.support.entity.ImageFileEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.gui.profile.DialogPhotoSelect;
import com.sevenheaven.iosswitch.ShSwitchView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.quanshu.exchange.support.chat.ChatConstant.Chat_ext_attr_photo;

/**
 * 创建群组
 * Created by xiniu003 on 2017/12/8.
 */

public class UpdateGroupActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.create_group_title)
    TextView createGroupTitle;
    @BindView(R.id.comment_group)
    LinearLayout commentGroup;
    @BindView(R.id.group_head_portrait)
    ImageView groupHeadPortrait;
    @BindView(R.id.group_name)
    EditText groupName;
    @BindView(R.id.group_intro_text)
    TextView groupIntroText;
    @BindView(R.id.group_intro_rel)
    RelativeLayout groupIntroRel;
    @BindView(R.id.group_classify_text)
    TextView groupClassifyText;
    @BindView(R.id.group_classify_rel)
    RelativeLayout groupClassifyRel;
    @BindView(R.id.openable_group_switch)
    ShSwitchView openSwitch;
    @BindView(R.id.group_owner_hand_over)
    RelativeLayout ownerHandOver;

    private String groupNameStr;//群昵称
    private String groupIntroStr = "";//群简介
    private GroupLabelEntity groupLabelEntity;//群类型 下标 - string
    private int openCheckInt;//是否需要审核
    private String groupAvatar = "";//群头像
    private GroupEntity groupEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_group);
        ButterKnife.bind(this);
        initIntent();
        initData();
        setSwitch();
        initListener();
    }

    private void initIntent() {
        groupEntity = (GroupEntity) getIntent().getSerializableExtra("GroupEntity");
    }

    private void initData() {
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .getGroupInfo(AppUtils.getSignParams(currentUser.getMemberid(), groupEntity.getHx_groupid() + ""), currentUser.getMemberid(), groupEntity.getHx_groupid() + "")
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<GroupEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<GroupEntity> response) {
                        groupEntity = response.getInfo();
                        setViewInfo();
                    }
                });
    }

    private void setViewInfo() {

        if (groupEntity != null) {
            GlideUtils.setRoundImageView(this, groupEntity.getGroup_photo(),
                    R.drawable.default_group_avatar, groupHeadPortrait);
            groupName.setText(groupEntity.getGroup_name());
            groupIntroStr = groupEntity.getGroup_introduce();
            groupIntroText.setText(groupEntity.getGroup_introduce());
            groupClassifyText.setText(groupEntity.getGroup_label_name());
            // 是否为公开群
            if (groupEntity.getVisible() == 1) {
                openSwitch.setOn(true);
                openCheckInt = 1;
            } else {
                openSwitch.setOn(false);
                openCheckInt = 0;
            }
            if (groupLabelEntity == null) {
                groupLabelEntity = new GroupLabelEntity();
            }
            groupLabelEntity.setId(Integer.parseInt(groupEntity.getGroup_label_id()));
            groupAvatar = groupEntity.getGroup_photo();
        }
    }

    private void setSwitch() {
        openSwitch.setOnSwitchStateChangeListener(isOn -> {
            boolean addGroupCheck = openSwitch.isOn();
            if (addGroupCheck == true) {
                openCheckInt = 1;
            } else {
                openCheckInt = 0;
            }
        });
    }

    private void doCommit() {
        if (groupNameStr.equals(groupEntity.getGroup_name()) &&
                groupIntroStr.equals(groupEntity.getGroup_introduce()) &&
                groupClassifyText.getText().toString().equals(groupEntity.getGroup_label_name()) &&
                groupAvatar.equals(groupEntity.getGroup_photo()) && openCheckInt == groupEntity.getVisible()) {
            ToastHelper.toast("未作出修改，不能提交");
            return;
        }

        if (TextUtils.isEmpty(groupNameStr)) {
            ToastHelper.toast("请输入群名称");
            return;
        }

        if (TextUtils.isEmpty(groupIntroStr)) {
            ToastHelper.toast("请输入群简介");
            return;
        }

        if (groupLabelEntity == null) {
            ToastHelper.toast("请选择群分类");
            return;
        }

        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .updateGroup(AppUtils.getSignParams(groupEntity.getHx_groupid(),
                        groupNameStr, groupIntroStr, groupAvatar, groupLabelEntity.getId() + "",
                        openCheckInt + ""), groupEntity.getHx_groupid(),
                        groupNameStr, groupIntroStr, groupAvatar, groupLabelEntity.getId() + "", openCheckInt)
                .compose(new BaseTransformer<>(this, true, false))
                .subscribe(new BaseObserver<BaseResponse<GroupEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<GroupEntity> response) {
//                        GroupEntity entity = response.getInfo();
//                        entity.setOwner(groupEntity.getOwner());
//                        entity.setVisible(openCheckInt);
//                        entity.setGroup_id(groupEntity.getGroup_id());

                        groupEntity.setGroup_name(groupNameStr);
                        groupEntity.setVisible(openCheckInt);
                        groupEntity.setGroup_introduce(groupIntroStr);
                        groupEntity.setGroup_label_id(groupLabelEntity.getId() + "");
                        GroupDao.getInstance().save(groupEntity);

                        ToastHelper.toast("群资料更新成功");

                        // 发透传消息给所有群成员
                        EMMessage cmdMsg = EMMessage.createSendMessage(EMMessage.Type.CMD);
                        //支持单聊和群聊，默认单聊，如果是群聊添加下面这行
                        cmdMsg.setChatType(EMMessage.ChatType.GroupChat);
                        String action = "group_visible";//action可以自定义
                        EMCmdMessageBody cmdBody = new EMCmdMessageBody(action);
                        cmdMsg.setTo(groupEntity.getHx_groupid());//发送给某个人
                        if (openCheckInt == 1) {
                            cmdMsg.setAttribute("visible", true);
                        } else {
                            cmdMsg.setAttribute("visible", false);
                        }
                        cmdMsg.addBody(cmdBody);
                        EMClient.getInstance().chatManager().sendMessage(cmdMsg);

                        doSendSystemMsg(openCheckInt);

                        finish();
                    }
                });
    }

    private void doSendSystemMsg(int visible) {
        EMMessage message;
        if (visible == 1) {
            message = EMMessage.createTxtSendMessage("群主打开群消息公开，群成员消息相互可见", groupEntity.getHx_groupid());
        } else {
            message = EMMessage.createTxtSendMessage("群主关闭群消息公开，群成员消息相互不可见", groupEntity.getHx_groupid());
        }
        message.setChatType(EMMessage.ChatType.GroupChat);
        message.setFrom("admin");
        message.setAttribute(ChatConstant.Chat_group_id, groupEntity.getGroup_id());
        message.setAttribute(ChatConstant.Chat_group_photo, groupEntity.getGroup_photo());
        message.setAttribute(ChatConstant.Chat_group_name, groupEntity.getGroup_name());
        message.setAttribute(ChatConstant.Chat_group_owner, groupEntity.getOwner());
        // 是不是公开群
        if (visible == 1) {
            message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, true);
        } else {
            message.setAttribute(ChatConstant.Chat_ext_attr_is_toAll, false);
        }
        message.setAttribute(ChatConstant.Chat_send_member_id, currentUser.getMemberid());
        message.setAttribute(Chat_ext_attr_photo, currentUser.getAvatar());
        message.setAttribute(ChatConstant.Chat_ext_attr_nickname, currentUser.getNickname());
        EMClient.getInstance().chatManager().saveMessage(message);
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        //提交
        RxViewHelper.getInstance().clicks(commentGroup, aVoid -> doCommit());

        //群 -头像
        RxViewHelper.getInstance().clicks(groupHeadPortrait, aVoid -> {
            doShowPhotoDialog();
        });

        RxViewHelper.getInstance().afterTextChangeEvents(groupName, textViewAfterTextChangeEvent -> {
            groupNameStr = groupName.getText().toString();
        });

        //群 -简介
        RxViewHelper.getInstance().clicks(groupIntroRel, aVoid -> {
            Intent intent = new Intent(UpdateGroupActivity.this, GroupIntroActivity.class);
            intent.putExtra("primeval", groupIntroText.getText().toString());
            startActivityForResult(intent, 7);
        });

        //群 -分类
        RxViewHelper.getInstance().clicks(groupClassifyRel, aVoid -> {
            Intent intent = new Intent(UpdateGroupActivity.this, GroupLabelActivity.class);
            if (groupLabelEntity != null) {
                intent.putExtra("GroupLabelEntity", groupLabelEntity);
            }
            startActivityForResult(intent, 8);
        });

        // 移交群主
        RxViewHelper.getInstance().clicks(ownerHandOver, aVoid -> doHandOverOwner());
    }

    private void doHandOverOwner() {
        Intent intent = new Intent(UpdateGroupActivity.this, HandOverGroupOwnerActivity.class);
        intent.putExtra("GroupEntity", groupEntity);
        startActivityForResult(intent, 9);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 7) {
                groupIntroStr = data.getStringExtra("bian");
                if (!TextUtils.isEmpty(groupIntroStr)) {
                    groupIntroText.setText(groupIntroStr);
                }
            } else if (requestCode == 8) {

                groupLabelEntity = (GroupLabelEntity) data.getSerializableExtra("GroupLabelEntity");
                groupClassifyText.setText(groupLabelEntity.getLabel_name());

            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                String path = selectList.get(0).getCutPath();
                GlideUtils.setRoundImageView(this, path, R.drawable.default_img, groupHeadPortrait);
                File file = new File(path);
                if (file != null && file.exists()) {
                    upLoadFile(file);
                } else {
                    ToastHelper.toast("上传图片错误");
                }
            } else if (requestCode == 9) {
                groupEntity = (GroupEntity) data.getSerializableExtra("GroupEntity");
                setViewInfo();
                finish();
            }
        }
    }

    private void doShowPhotoDialog() {
        DialogPhotoSelect dialogPhotoSelect = new DialogPhotoSelect(this);
        dialogPhotoSelect.show();
        dialogPhotoSelect.getAlbumSubject().subscribe(o -> {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .enableCrop(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1, 1)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();

        });
        dialogPhotoSelect.getTakePhotoSubject().subscribe(o -> {
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .enableCrop(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1, 1)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
    }

    private void upLoadFile(File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part avatar = MultipartBody.Part.createFormData("img", file.getName(), requestFile);
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .uploadGroupImg(avatar)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<ImageFileEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ImageFileEntity> response) {
                        ImageFileEntity data = response.getInfo();
                        groupAvatar = data.getImgurl();
                    }
                });
    }

}
